package eu.fishcode.android.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;

public class CommonAdb {

	public static String getDevice() {
		boolean bList = false;
		try {
			if (Utils.isLinux()) {
				final String cmdLine = "./Tools/Linux/adb devices";
				final Process p = Runtime.getRuntime().exec(cmdLine);
				final BufferedReader in = new BufferedReader(
						new InputStreamReader(p.getInputStream()));

				String line;
				while ((line = in.readLine()) != null) {
					if (bList) {
						return line;
					}
					bList = line.contains("List of devices attached");
					Utils.logger.log(Level.INFO, line);
				}
			}

		} catch (final IOException e) {
			Utils.logger.log(Level.SEVERE, "Tools Linux adb failed", e);
		}
		return "";
	}

	public static boolean pull(String remoteFile, String localDestination) {
		String cmdLine = null;
		if (Utils.isLinux()) {
			cmdLine = "./Tools/Linux/adb";
		}
		cmdLine += " pull " + remoteFile + " " + localDestination;
		try {
			final Process p = Runtime.getRuntime().exec(cmdLine);

			final BufferedReader stdInput = new BufferedReader(
					new InputStreamReader(p.getInputStream()));

			final BufferedReader stdError = new BufferedReader(
					new InputStreamReader(p.getErrorStream()));

			String s;
			while ((s = stdInput.readLine()) != null) {
				System.out.println(s);
			}

			while ((s = stdError.readLine()) != null) {
				System.out.println(s);
			}

		} catch (final IOException e) {
			System.out.println("exception happened - here's what I know: ");
			e.printStackTrace();
		}
		return true;
	}

	public static boolean push(String localFile, String remoteDestination) {
		String cmdLine = null;
		if (Utils.isLinux()) {
			cmdLine = "./Tools/Linux/adb";
		}
		cmdLine += " push " + localFile + " " + remoteDestination;
		try {
			final Process p = Runtime.getRuntime().exec(cmdLine);

			final BufferedReader stdInput = new BufferedReader(
					new InputStreamReader(p.getInputStream()));

			final BufferedReader stdError = new BufferedReader(
					new InputStreamReader(p.getErrorStream()));

			String s;
			while ((s = stdInput.readLine()) != null) {
				System.out.println(s);
			}

			while ((s = stdError.readLine()) != null) {
				System.out.println(s);
			}

		} catch (final IOException e) {
			System.out.println("exception happened - here's what I know: ");
			e.printStackTrace();
		}
		return true;
	}

}
